using System;
using Jalal.Library.DataStructure;
using Jalal.Library.Data;
using BCGC.DAL;
using Jalal.Library.Utility;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace BCGC.BLL.Forum
{

    public class ForumManager
    {
        public static bool SavePost(string tag, int categoryID, int userID, string title, string content, DateTime date, bool isReply, int displayOrder, int replyTOID,bool isActive)
        {
            bool result = true;
            PostTag postTag = new PostTag();
            postTag.Tag = tag;
            

            Post post = new Post();
            post.CategoryID = categoryID;
            post.UserID = userID;
            post.PostTitle = title;
            post.PostContent = content;
            post.PostDate = date;
            post.IsReply = isReply;
            post.DisplayOrder = displayOrder;
            post.ReplyTOID = replyTOID;
            post.IsActive = isActive;

            PostTag oldTag = null;
            if (!string.IsNullOrEmpty(tag) || tag != "")
            {
                oldTag = PostTag.GetByTagName(tag);
            }

            PostCategory postcategory = null;
            if (replyTOID == 0)
            {
                postcategory = PostCategory.GetPostCategoryByID(categoryID);

            }
            

            DataFactory.GetDataMiner().BeginTransaction(false);
            try
            {
                int newID = 0;
                if (oldTag != null) // Old Tag
                {
                    postTag.TagWeight = oldTag.TagWeight + 1;
                    newID = oldTag.PostTagID;
                    if (!postTag.Update()) { throw new Exception("Post Tag Saving Failed"); }
                }
                else
                {
                    if (!string.IsNullOrEmpty(tag) || tag!="")
                    {
                        postTag.TagWeight = 1;
                        newID = postTag.Create();
                        if (newID <= 0) { throw new Exception("Post Tag Saving Failed"); }
                    }
                }


                post.Tag = newID;
               
                if (!post.Save()) { throw new Exception("Post Saving Failed"); }

                if (post.IsReply)
                {
                    if (!post.UpdateLatestPost(post.ReplyTOID, post.PostID)) { throw new Exception("Latest Post Saving Failed"); }
                }
                else
                {
                    if (!post.UpdateLatestPost(post.PostID, post.PostID)) { throw new Exception("Latest Post Saving Failed"); }
                }

                if (postcategory != null)
                {
                    postcategory.TotalPost = postcategory.TotalPost + 1;
                    if (!postcategory.Save()) { throw new Exception("Post Category Saving Failed"); }
                }

                DataFactory.GetDataMiner().CommitTransaction();
            }
            catch
            {
                DataFactory.GetDataMiner().RollBackTransaction();
                result = false;
            }

            return result;
        }

        public static ReadWriteCustomCollection<PostCategory> GetAllCategoryTotalListing()
        {
            return PostCategory.GetAll();
        }

        public static ReadWriteCustomCollection<Post> GetAllRecentPostByCategory(int categoryID)
        {

            return Post.GetAllByCategory(categoryID);
        }

        public static ReadWriteCustomCollection<Post> GetAllPost(int? categoryId, int? userID, string tag, string sortColumn, string sortDirection, int currentPageIndex, int pageSize, bool showReply, out int totalRecords)
        {

            return Post.GetAll(categoryId, userID, tag, sortColumn, sortDirection, currentPageIndex, pageSize, showReply, out totalRecords);
        }

        public static ReadWriteCustomCollection<Post> GetPostDetailsByID(int postID)
        {
            return Post.GetPostDetailsByID(postID);
        }

        public static Post GetPostByID(int postID)
        {
            return Post.GetByID(postID);
        }

        public static bool DeactivatePost(int postID)
        {
            bool result = true;
            DataFactory.GetDataMiner().BeginTransaction(false);
            try
            {
                if (Post.DeactivatePost(postID)) { throw new Exception("Post Deactivation Failed"); }
            }
            catch
            {
                DataFactory.GetDataMiner().RollBackTransaction();
                result = false;
            }

            return result;
        }

        public static PostCategory GetPostCategoryByID(int categoryID)
        {
            return PostCategory.GetPostCategoryByID(categoryID);
        }        

        public static bool DeletePost(int postID)
        {
            return Post.Delete(postID);
        }

        public static bool CreateNewPostCategory(string categoryName, int totalPost, bool isActive,string description)
        {
            PostCategory postCat = new PostCategory();
            postCat.CategoryName = categoryName;
            postCat.TotalPost = totalPost;
            postCat.IsActive = isActive;
            postCat.Description = description;
            return (postCat.Create() > 0 ? true : false);
        }

        public static bool SavePostCategory(PostCategory postCat)
        {
            return postCat.Save();
        }

        public static ReadWriteCustomCollection<PostCategoryListing> GetAllRecentPosts(int categoryID, string sortBy, string sortDirection, int currentPage, int pageSize, out int totalCount)
        {

            return PostCategoryListing.GetAllRecentPosts(categoryID, sortBy, sortDirection, currentPage, pageSize,out totalCount);
        }

        public static ReadWriteCustomCollection<LatestPosts> GetAllLatestPost(int categoryID, string sortColumn, string sortDirection, int currentPage, int pazeSize, out int totalCount)
        {
            return LatestPosts.GetAllLatestPost(categoryID, sortColumn, sortDirection, currentPage, pazeSize, out totalCount);
        }

        public static bool ReportAbuse(int postID,int userID,string comment,bool isActionTaken)
        {
            AbusePost abuse = new AbusePost();
            abuse.PostID = postID;
            abuse.UserID = userID;
            abuse.Comment = comment;
            abuse.IsActionTaken = isActionTaken;
            return abuse.Save();
        }

        public static bool TakeActionOnAbusePost(int abusePostID, int postID,bool isActionTaken)
        {
            bool result = true;
            Post post=Post.GetByID(postID);
            AbusePost abusePost=AbusePost.GetAbusePostByID(abusePostID);
            DataFactory.GetDataMiner().BeginTransaction(false);
            try
            {
                post.IsActive = !isActionTaken;
                if (!post.Save()) { throw new Exception("Failed To Save Post"); }

                abusePost.IsActionTaken = isActionTaken;
                if (!abusePost.Save()) { throw new Exception("Failed To Save Abuse Post");  }
                
            }
            catch
            {
                DataFactory.GetDataMiner().RollBackTransaction();
                result = false;
            }

            return result;

        }

        public static string GetFormatedPost(string content)
        {
            StringBuilder message = new StringBuilder();
            string quoteUserName = string.Empty;
            string quoteContent = string.Empty;

            int start = 0;
            int end = 0;

            content = FormatSpecialCharacter(content);
            start = content.IndexOf(@"<quote>");

            message.Append("<table style='width:100%;'>");

            while (start >= 0)
            {
                message.Append("<tr>");
                if (start > 0) // Custom Text Exists
                {
                    message.Append("<td align='left' valign='top'>");
                    message.Append(content.Substring(0, start - 1));
                    content = content.Remove(0, start - 1).Trim();
                    message.Append("</td>");
                }

                else
                {
                    message.Append("<td align='center' valign='top'>");
                    start = start + 7;
                    end = content.IndexOf("</quote>");
                    quoteContent = content.Substring(start, (end - start));
                    end = end + 8;
                    content = content.Remove(0, end).Trim();
                    StringBuilder quoteMessage = new StringBuilder();
                    quoteMessage.Append("<table border='1' class='quote'>");
                    quoteMessage.Append("<tr>");
                    quoteMessage.Append("<td>");
                    quoteMessage.Append(quoteContent);
                    quoteMessage.Append("</td>");
                    quoteMessage.Append("</tr>");
                    quoteMessage.Append("</table>");
                    message.Append(quoteMessage.ToString());
                    message.Append("</td>");
                }

                start = content.IndexOf(@"<quote>");
                message.Append("</tr>");

            }
            message.Append("</table>");

            message.Append(content);
            return message.ToString();
        }

        public static bool IsValidPost(string content)
        {
            Match match=Regex.Match(content, @"<(.|\n)*?>");
            if (match.Success)
                return false;
            else
                return true;
        }

        private static string FormatSpecialCharacter(string content)
        {
            //Replace UnderLine
            content = content.Replace("[u]", "<u>").Replace("[/u]", "</u>");
            //Replace NewLIne
            content = content.Replace("[br /]", "<br />");
            //Replace Quote
            content = content.Replace("[quote]", "<quote>").Replace("[/quote]", "</quote>");
            //Replace Italic
            content = content.Replace("[i]", "<i>").Replace("[/i]", "</i>");
            //Replace Bold
            content = content.Replace("[b]", "<b>").Replace("[/b]", "</b>");
            //Replace image
            content = content.Replace("[image][", "<img src='").Replace("][/image]", "' />");
            content = content.Replace("[a]", "<a>").Replace("[/a]", "</a>");


            content = content.Replace("[a href='", "<a href='").Replace("']", "'>");

            //int startIndex=content.IndexOf("[a href='");
            //if (startIndex > 0)
            //{
            //    int endIndex = content.IndexOf("']");
            //    content = content.Substring(startIndex, endIndex - startIndex);
            //}

            //Replace imotions
            content = content.Replace(":arrow:", @"<img src='./Emotions/icon_arrow.gif' border='0' />");
            content = content.Replace(":D", @"<img src='./Emotions/icon_biggrin.gif' border='0' />");
            content = content.Replace(":?", @"<img src='./Emotions/icon_confused.gif' border='0' />");
            content = content.Replace(":cool:", @"<img src='./Emotions/icon_cool.gif' border='0' />");
            content = content.Replace(":cry:", @"<img src='./Emotions/icon_cry.gif' border='0' />");
            content = content.Replace(":eek:", @"<img src='./Emotions/icon_eek.gif' border='0' />");
            content = content.Replace(":evil:", @"<img src='./Emotions/icon_evil.gif' border='0' />");
            content = content.Replace(":exclaim:", @"<img src='./Emotions/icon_exclaim.gif' border='0' />");
            content = content.Replace(":idea:", @"<img src='./Emotions/icon_idea.gif' border='0' />");
            content = content.Replace(":lol:", @"<img src='./Emotions/icon_lol.gif' border='0' />");
            content = content.Replace(":mad:", @"<img src='./Emotions/icon_mad.gif' border='0' />");
            content = content.Replace(":mrgreen:", @"<img src='./Emotions/icon_mrgreen.gif' border='0' />");
            content = content.Replace(":neutral:", @"<img src='./Emotions/icon_neutral.gif' border='0' />");
            content = content.Replace(":question:", @"<img src='./Emotions/icon_question.gif' border='0' />");
            content = content.Replace(":razz:", @"<img src='./Emotions/icon_razz.gif' border='0' />");
            content = content.Replace(":redface:", @"<img src='./Emotions/icon_redface.gif' border='0' />");
            content = content.Replace(":rolleyes:", @"<img src='./Emotions/icon_rolleyes.gif' border='0' />");
            content = content.Replace(":sad:", @"<img src='./Emotions/icon_sad.gif' border='0' />");
            content = content.Replace(":smile:", @"<img src='./Emotions/icon_smile.gif' border='0' />");
            content = content.Replace(":surprised:", @"<img src='./Emotions/icon_surprised.gif' border='0' />");
            content = content.Replace(":twisted:", @"<img src='./Emotions/icon_twisted.gif' border='0' />");
            content = content.Replace(":wink:", @"<img src='./Emotions/icon_wink.gif' border='0' />");
            content = content.Replace(":worshippy:", @"<img src='./Emotions/worshippy.gif' border='0' />");

            return content;
        }

        
    }

}
